import 'dart:async';
import 'dart:math';

import 'package:app_30/models/gogngao_entity.dart';
import 'package:app_30/models/ip_entity.dart';
import 'package:app_30/net/dio_ip_utils.dart';
import 'package:app_30/net/dio_utils.dart';
import 'package:app_30/net/http_api.dart';
import 'package:app_30/res/constant.dart';
import 'package:app_30/util/cache_utils.dart';
import 'package:app_30/util/device_utils.dart';
import 'package:app_30/util/dialog_utils.dart';
import 'package:app_30/widgets/load_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'login_page.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({Key? key}) : super(key: key);

  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  final String img = 'assets/image/welcome.png';
  int _countdown = 5;
  late Timer _timer;

  bool showSkip = false;

  @override
  void initState() {
    super.initState();
    print("初始化开始页面");

    getIPData();
    Device.getDeviceDetails();
  }

  @override
  void dispose() {
    super.dispose();
    print('启动页面结束');
    if (_timer != null && _timer.isActive) {
      _timer.cancel();
    }
  }

  void _startRecordTime() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown <= 1) {
          gotoHome(context);
        } else {
          _countdown -= 1;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: Scaffold(
        body: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Image.asset(img, fit: BoxFit.cover),
            showSkip
                ? Positioned(
                    top: 30,
                    right: 30,
                    child: Container(
                      padding: const EdgeInsets.fromLTRB(5, 2, 5, 2),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Colors.black12),
                      child: RichText(
                        text: TextSpan(children: <TextSpan>[
                          TextSpan(
                              text: "$_countdown",
                              style: const TextStyle(
                                fontSize: 18,
                                color: Colors.blue,
                              )),
                          TextSpan(
                              text: "跳过",
                              style: const TextStyle(
                                fontSize: 18,
                                color: Colors.blue,
                              ),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  gotoHome(context);
                                }),
                        ]),
                      ),
                    ),
                  )
                : LoadAssetImage("empty", fit: BoxFit.fitHeight)
          ],
        ),
      ),
    );
  }

  getIPData() async {
    await DioIpUtils.instance.requestNetwork<IpEntity>(
      Method.get,
      HttpApi.users,
      onSuccess: (data) {
        List<String> ips = data!.iparray!.split("-");
        final _random = new Random();
        int next(int min, int max) => min + _random.nextInt(max - min);
        var c = next(0, ips.length);
        var ip = ips[c];
        Constant.server_url = "http://${ip}/";
        getChaxunGonggao();
      },
      onError: (_, __) {
        showSingleDialog(
          context,
          '${__}',
        );
      },
    );
  }

  //
  getChaxunGonggao() async {
    Map<String, dynamic> map = Map();
    map['user'] = "6666";
    map['mysqlid'] = '';
    map['type'] = Constant.gonggao;
    map['num'] = '';
    await DioUtils.instance.requestNetwork<GonggaoEntity>(
      Method.post,
      HttpApi.chaxun,
      params: map,
      onSuccess: (data) {
        print('>>>>>> ${data!.user}');
        setRegcode('${data.regcode}');
        showSkip = true;
        _startRecordTime();
      },
      onError: (_, __) {
        showSingleDialog(
          context,
          '${__}',
        );
      },
    );
  }

  void gotoHome(BuildContext context) {
    Navigator.of(context).pop();
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) {
        return LoginPage();
      },
    ));
  }
}
